package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"news/models"
	"strconv"
	"time"
)

type NewsController struct {
	beego.Controller
}
type JsonMsg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewsController) Add() {
	title := c.GetString("title")
	times := time.Now()
	cate := c.GetString("cate")
	news := models.News{
		Title: title,
		Times: times,
		Cate:  cate,
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *NewsController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 3)
	var total int64
	query := models.DB.Model(&models.News{})
	JsonData := make(map[string]interface{})
	key := "news-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		err = query.Count(&total).Error
		if err != nil {
			c.Data["json"] = JsonMsg{
				Code: 500,
				Msg:  "总数查询失败",
				Data: nil,
			}
			c.ServeJSON()
		}
		var news []models.News
		err = query.Offset((page - 1) * pageSize).Limit(pageSize).Find(&news).Error
		if err != nil {
			c.Data["json"] = JsonMsg{
				Code: 500,
				Msg:  "分页失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {
			JsonData["news"] = news
			JsonData["total"] = total
			c.Data["json"] = JsonMsg{
				Code: 200,
				Msg:  "分页成功",
				Data: JsonData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), key)
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "查询成功",
			Data: JsonData,
		}
		c.ServeJSON()
	}

}
func (c *NewsController) Update() {
	title := c.GetString("title")
	times := time.Now()
	cate := c.GetString("cate")
	id, _ := c.GetInt("id")
	news := models.News{
		Title: title,
		Times: times,
		Cate:  cate,
	}
	err := models.DB.Where("id=?", id).Updates(&news).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
